/**
 * 所有版权归 广西梧州 陈锦韬 所有
 *
 * @Title: RxBCryptPasswordEncoder
 * @Package com.rx.core.bean
 * @Description: 加解密
 * @author: 陈锦韬
 * @date: 2021\6\25 0025
 * @version V1.0
 * @Copyright: 2021 陈锦韬  All rights reserved.
 */
package com.rx.core.bean;

import com.rx.core.controller.OAuthController;
import com.rx.core.enm.RX_ENABLE;
import java.util.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import java.security.NoSuchAlgorithmException;

/**
 * @author: Administrator
 * @Description: 加解密
 * @date: 2021\6\25 0025
 */
public class RxBCryptPasswordEncoder extends BCryptPasswordEncoder {
    public static final String E_PREFIX = "@@@";
    public static final String E_SUFFIX = "###";

    public static Cipher cipher;

    @Autowired
    RxConfigBean rxConfigBean;

    @Autowired
    RxTokenConfig rxTokenConfig;

    @Override
    public String encode(CharSequence rawPassword) {
        return encode(true,rawPassword);
    }

    /**
     * 传入加密后的密码，进行解密     pwOrUn加密后的密码
     */
    public synchronized String passwordAndUsernameRsaDecode(boolean fromConfig, String pwOrUn) {
        try {
            // 解密 TODO:将私钥放进redis
            cipher = getCipher();
            if (fromConfig){
                cipher.init(Cipher.DECRYPT_MODE, OAuthController.privateKeyForSecret);
            }else {
                cipher.init(Cipher.DECRYPT_MODE, OAuthController.privateKey);
            }

            byte[] rawPasswordByte = cipher.doFinal(Base64.getDecoder().decode(pwOrUn));
            pwOrUn = new String(rawPasswordByte);
        }catch (Exception e){
            throw new RuntimeException("Rsa密码解密失败");
        }
        return pwOrUn;
    }

    public static synchronized Cipher getCipher()
            throws NoSuchAlgorithmException, NoSuchPaddingException {
        if(cipher!=null){
            return cipher;
        }
        return Cipher.getInstance("RSA", new BouncyCastleProvider());
    }

    @Override
    public boolean matches(CharSequence rawPassword, String encodedPassword) {
        return matches(true,rawPassword,encodedPassword);
    }
    public String decodePassword(boolean fromConfig, CharSequence rawPassword){
        if (RX_ENABLE.isEnable(rxConfigBean.getRxNeedRsa())){
            rawPassword = passwordAndUsernameRsaDecode(fromConfig,rawPassword.toString());
        }
        return E_PREFIX + rawPassword + E_SUFFIX;
    }
    public boolean matches(boolean fromConfig, CharSequence rawPassword, String encodedPassword) {
        // 密码加前缀。
        return super.matches(decodePassword(fromConfig,rawPassword),encodedPassword);
    }

    public String encode(boolean fromConfig, CharSequence rawPassword) {
        return super.encode(decodePassword(fromConfig,rawPassword));
    }
}
